package org.corey.share.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.corey.share.db.service.AuthServiceImpl;
import org.corey.share.misc.Common;
import org.corey.share.misc.Constants;

public class AuthFilter implements Filter {
	private FilterConfig config;
	private String loginPath;
	private String loginCheck;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String requestPath = httpRequest.getRequestURI().toString();
		if (httpRequest.getSession().getAttribute(Constants.USER_KEY) == null
				&& AuthServiceImpl.getInstance().isRequireAdminPermission(
						requestPath)) {
			httpResponse.sendRedirect(loginPath);
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		loginPath = this.config.getInitParameter("loginPath");
		if (Common.isEmpty(loginPath)) {
			throw new IllegalStateException(
					"the AuthFIlter's loginPath is unsetted");
		}
		loginCheck = this.config.getInitParameter("loginCheck");
		if (Common.isEmpty(loginCheck)) {
			throw new IllegalStateException(
					"the AuthFIlter's loginCheck is unsetted");
		}
	}
}
